import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  TextInput,
  Modal,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Simple text-based icons
const Icon = ({ name, size = 24, color = '#000' }: { name: string; size?: number; color?: string }) => {
  const iconMap: { [key: string]: string } = {
    'arrow-back': '⬅️',
    'add': '+',
    'arrow-down': '▼',
    'arrow-up': '▲',
    'calendar': '📅',
  };

  return (
    <Text style={{ fontSize: size, color, textAlign: 'center' }}>
      {iconMap[name] || '📱'}
    </Text>
  );
};

interface DropdownOption {
  label: string;
  value: string;
}

const ZhuanzhengApplication: React.FC = () => {
  const navigation = useNavigation();
  const [formData, setFormData] = useState({
    applicant: '',
    department: '',
    position: '',
    entryDate: '',
    understanding: '',
    workPlan: '',
    suggestions: '',
  });

  // Dropdown states
  const [showDepartmentDropdown, setShowDepartmentDropdown] = useState(false);
  const [showPositionDropdown, setShowPositionDropdown] = useState(false);
  const [showDatePicker, setShowDatePicker] = useState(false);

  // Date picker state
  const [selectedYear, setSelectedYear] = useState(2022);
  const [selectedMonth, setSelectedMonth] = useState(8);

  // Dropdown options
  const departmentOptions: DropdownOption[] = [
    { label: '技术部', value: '技术部' },
    { label: '人事部', value: '人事部' },
    { label: '财务部', value: '财务部' },
    { label: '市场部', value: '市场部' },
    { label: '运营部', value: '运营部' },
  ];

  const positionOptions: DropdownOption[] = [
    { label: '技术员', value: '技术员' },
    { label: '工程师', value: '工程师' },
    { label: '高级工程师', value: '高级工程师' },
    { label: '技术主管', value: '技术主管' },
    { label: '技术经理', value: '技术经理' },
  ];

  const years = Array.from({ length: 10 }, (_, i) => 2020 + i);
  const months = Array.from({ length: 12 }, (_, i) => i + 1);

  const getDaysInMonth = (year: number, month: number) => {
    return new Date(year, month, 0).getDate();
  };

  const handleOptionSelect = (field: string, value: string) => {
    setFormData({ ...formData, [field]: value });
    setShowDepartmentDropdown(false);
    setShowPositionDropdown(false);
  };

  const handleDateSelect = (day: number) => {
    const formattedMonth = selectedMonth.toString().padStart(2, '0');
    const formattedDay = day.toString().padStart(2, '0');
    const newDate = `${selectedYear}-${formattedMonth}-${formattedDay}`;
    
    // 验证日期不能大于当前日期
    const selectedDate = new Date(selectedYear, selectedMonth - 1, day);
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    
    if (selectedDate > currentDate) {
      Alert.alert('提示', '入职时间不能大于当前日期');
      return;
    }
    
    setFormData({ ...formData, entryDate: newDate });
    setShowDatePicker(false);
  };

  const validateForm = (): boolean => {
    if (!formData.applicant.trim()) {
      Alert.alert('提示', '请填写申请人姓名');
      return false;
    }
    if (!formData.understanding.trim()) {
      Alert.alert('提示', '请填写对本岗位的理解');
      return false;
    }
    if (!formData.workPlan.trim()) {
      Alert.alert('提示', '请填写个人工作规划');
      return false;
    }
    if (!formData.suggestions.trim()) {
      Alert.alert('提示', '请填写对公司的意见和建议');
      return false;
    }
    return true;
  };

  const saveToLocalStorage = async (data: any) => {
    try {
      const existingData = await AsyncStorage.getItem('applications');
      const applications = existingData ? JSON.parse(existingData) : [];
      
      const newApplication = {
        id: Date.now().toString(),
        type: '转正申请',
        title: '转正申请',
        applicant: formData.applicant,
        details: `${formData.department} - ${formData.position}`,
        applicationTime: new Date().toLocaleString('zh-CN'),
        status: '待审批',
        data: data,
        category: '人事管理',
      };
      
      applications.unshift(newApplication);
      await AsyncStorage.setItem('applications', JSON.stringify(applications));
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      await saveToLocalStorage(formData);
      Alert.alert('提示', '提交完成', [
        {
          text: '确定',
          onPress: () => (navigation as any).navigate('AllApplications'),
        },
      ]);
    } catch (error) {
      Alert.alert('错误', '提交失败，请重试');
    }
  };

  const renderDropdown = (
    visible: boolean,
    options: DropdownOption[],
    onSelect: (value: string) => void,
    onClose: () => void
  ) => (
    <Modal
      visible={visible}
      transparent={true}
      animationType="fade"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.dropdownContainer}>
          {options.map((option, index) => (
            <TouchableOpacity
              key={index}
              style={styles.dropdownOption}
              onPress={() => onSelect(option.value)}
            >
              <Text style={styles.dropdownOptionText}>{option.label}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </TouchableOpacity>
    </Modal>
  );

  const renderDatePicker = () => {
    const daysInMonth = getDaysInMonth(selectedYear, selectedMonth);
    const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

    return (
      <Modal
        visible={showDatePicker}
        transparent={true}
        animationType="slide"
        onRequestClose={() => setShowDatePicker(false)}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={() => setShowDatePicker(false)}
        >
          <View style={styles.datePickerContainer}>
            {/* Header with confirm button */}
            <View style={styles.datePickerHeader}>
              <Text style={styles.datePickerTitle}>选择入职时间</Text>
              <TouchableOpacity onPress={() => setShowDatePicker(false)}>
                <Text style={styles.confirmButton}>确定</Text>
              </TouchableOpacity>
            </View>
            
            {/* Year and Month Selector */}
            <View style={styles.dateSelectorHeader}>
              <View style={styles.dateSelector}>
                <Text style={styles.dateSelectorLabel}>年份:</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                  <View style={styles.dateOptions}>
                    {years.map(year => (
                      <TouchableOpacity
                        key={year}
                        style={[
                          styles.dateOption,
                          selectedYear === year && styles.selectedDateOption
                        ]}
                        onPress={() => setSelectedYear(year)}
                      >
                        <Text style={[
                          styles.dateOptionText,
                          selectedYear === year && styles.selectedDateOptionText
                        ]}>
                          {year}
                        </Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                </ScrollView>
              </View>
              
              <View style={styles.dateSelector}>
                <Text style={styles.dateSelectorLabel}>月份:</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                  <View style={styles.dateOptions}>
                    {months.map(month => (
                      <TouchableOpacity
                        key={month}
                        style={[
                          styles.dateOption,
                          selectedMonth === month && styles.selectedDateOption
                        ]}
                        onPress={() => setSelectedMonth(month)}
                      >
                        <Text style={[
                          styles.dateOptionText,
                          selectedMonth === month && styles.selectedDateOptionText
                        ]}>
                          {month}
                        </Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                </ScrollView>
              </View>
            </View>

            {/* Days Grid */}
            <View style={styles.daysContainer}>
              <View style={styles.weekDays}>
                {['日', '一', '二', '三', '四', '五', '六'].map(day => (
                  <Text key={day} style={styles.weekDayText}>{day}</Text>
                ))}
              </View>
              <View style={styles.daysGrid}>
                {days.map(day => (
                  <TouchableOpacity
                    key={day}
                    style={styles.dayButton}
                    onPress={() => handleDateSelect(day)}
                  >
                    <Text style={styles.dayButtonText}>{day}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </Modal>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={20} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>转正申请</Text>
        <View style={styles.headerSpacer} />
      </View>

      {/* Content */}
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* Basic Information Section */}
        <View style={styles.section}>
          <View style={styles.infoRow}>
            <Text style={styles.label}>申请人</Text>
            <TextInput
              style={styles.textInput}
              placeholder="请输入申请人姓名"
              placeholderTextColor="#999"
              value={formData.applicant}
              onChangeText={(text) => setFormData({...formData, applicant: text})}
            />
          </View>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowDepartmentDropdown(true)}
          >
            <Text style={styles.label}>所在部门</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.department}</Text>
              <Icon name="arrow-down" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowPositionDropdown(true)}
          >
            <Text style={styles.label}>岗位</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.position}</Text>
              <Icon name="arrow-down" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowDatePicker(true)}
          >
            <Text style={styles.label}>入职时间</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.entryDate}</Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
        </View>

        {/* Text Input Sections */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>对本岗位的理解</Text>
          <TextInput
            style={styles.textArea}
            placeholder="请输入"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            value={formData.understanding}
            onChangeText={(text) => setFormData({...formData, understanding: text})}
          />
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>个人工作规划</Text>
          <TextInput
            style={styles.textArea}
            placeholder="请输入"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            value={formData.workPlan}
            onChangeText={(text) => setFormData({...formData, workPlan: text})}
          />
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>对公司的意见和建议</Text>
          <TextInput
            style={styles.textArea}
            placeholder="请输入"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            value={formData.suggestions}
            onChangeText={(text) => setFormData({...formData, suggestions: text})}
          />
        </View>

        {/* Approval Process Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>审批流程</Text>
          <View style={styles.approvalFlow}>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>1</Text>
              </View>
              <Text style={styles.flowLabel}>发起人</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>2</Text>
              </View>
              <Text style={styles.flowLabel}>部门领导</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>3</Text>
              </View>
              <Text style={styles.flowLabel}>人事部</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>4</Text>
              </View>
              <Text style={styles.flowLabel}>财务部</Text>
            </View>
          </View>
        </View>

        {/* CC Recipients Section */}
        <View style={styles.section}>
          <View style={styles.ccHeader}>
            <Text style={styles.sectionTitle}>抄送人</Text>
            <TouchableOpacity style={styles.addButton}>
              <Icon name="add" size={20} color="#333" />
            </TouchableOpacity>
          </View>
        </View>

        {/* Submit Button */}
        <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
          <Text style={styles.submitButtonText}>提交</Text>
        </TouchableOpacity>
      </ScrollView>

      {/* Dropdowns */}
      {renderDropdown(
        showDepartmentDropdown,
        departmentOptions,
        (value) => handleOptionSelect('department', value),
        () => setShowDepartmentDropdown(false)
      )}
      {renderDropdown(
        showPositionDropdown,
        positionOptions,
        (value) => handleOptionSelect('position', value),
        () => setShowPositionDropdown(false)
      )}
      {renderDatePicker()}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerSpacer: {
    width: 28,
  },
  content: {
    flex: 1,
    paddingHorizontal: 16,
  },
  section: {
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  label: {
    fontSize: 16,
    color: '#333',
    width: 80,
  },
  textInput: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    textAlign: 'right',
  },
  infoValue: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  valueText: {
    fontSize: 16,
    color: '#333',
    marginRight: 8,
  },
  arrow: {
    fontSize: 18,
    color: '#999',
  },
  separator: {
    height: 1,
    backgroundColor: '#e0e0e0',
  },
  textArea: {
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: '#333',
    minHeight: 100,
    textAlignVertical: 'top',
  },
  approvalFlow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  flowStep: {
    alignItems: 'center',
    flex: 1,
  },
  flowNode: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#6c5ce7',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 8,
  },
  flowNodeText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  flowLabel: {
    fontSize: 12,
    color: '#333',
    textAlign: 'center',
  },
  flowArrow: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 20,
  },
  arrowText: {
    fontSize: 18,
    color: '#999',
  },
  ccHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  addButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#f5f5f5',
    alignItems: 'center',
    justifyContent: 'center',
  },
  submitButton: {
    backgroundColor: '#6c5ce7',
    borderRadius: 8,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 32,
    marginBottom: 32,
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  dropdownContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 8,
    minWidth: 200,
    maxHeight: 300,
  },
  dropdownOption: {
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  dropdownOptionText: {
    fontSize: 16,
    color: '#333',
  },
  datePickerContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    padding: 20,
    width: '100%',
    maxHeight: '80%',
  },
  datePickerHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  datePickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#6c5ce7',
    fontWeight: '600',
  },
  dateSelectorHeader: {
    marginBottom: 20,
  },
  dateSelector: {
    marginBottom: 15,
  },
  dateSelectorLabel: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 8,
  },
  dateOptions: {
    flexDirection: 'row',
  },
  dateOption: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    marginRight: 8,
    borderRadius: 6,
    backgroundColor: '#f5f5f5',
  },
  selectedDateOption: {
    backgroundColor: '#6c5ce7',
  },
  dateOptionText: {
    fontSize: 14,
    color: '#333',
  },
  selectedDateOptionText: {
    color: '#fff',
    fontWeight: '600',
  },
  daysContainer: {
    flex: 1,
  },
  weekDays: {
    flexDirection: 'row',
    marginBottom: 10,
  },
  weekDayText: {
    flex: 1,
    textAlign: 'center',
    fontSize: 14,
    fontWeight: '600',
    color: '#666',
  },
  daysGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  dayButton: {
    width: '14.28%',
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 8,
  },
  dayButtonText: {
    fontSize: 16,
    color: '#333',
  },
});

export default ZhuanzhengApplication;

